import { ForbiddenException, Injectable, Inject } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { Friend } from './entities/friend.entity';
// import { Socket } from './entities/socket.entity';
import { RedisClientType } from 'redis';
import { Message } from './entities/message.entity';
import { Apply } from './entities/apply.entity';
@Injectable()
export class FriendService {
  constructor(
    private userService: UserService,

    @Inject('REDIS_CLIENT')
    private redisClient: RedisClientType,

    @InjectRepository(Friend)
    private readonly friendRepository: Repository<Friend>,

    @InjectRepository(Message)
    private readonly messageRepository: Repository<Message>,

    @InjectRepository(Apply)
    private readonly applyRepository: Repository<Apply>,
  ) {}
  // 创建用户
  async create(body) {
    const { user, friend } = body;
    const sendFriend = await this.userService.findOne(friend);
    // 去添加好友
    const tempSendFriend = await this.friendRepository.create({ user });
    tempSendFriend.friend = [sendFriend];
    this.friendRepository.save(tempSendFriend);
    // 好友也要添加自己 也就是双向添加
    const responseFriend = await this.userService.findOne(user);
    const tempResponceFriend = await this.friendRepository.create({ friend });
    tempResponceFriend.friend = [responseFriend];
    this.friendRepository.save(tempResponceFriend);
    return '添加好友成功';
  }
  // 创建群组
  async createGroup(body) {
    console.log('1111111', body);
    const params = {
      ...body,
      isGroup: true,
    };
    const tempGroup = await this.friendRepository.create(params);
    return this.friendRepository.save(tempGroup);
  }
  // 申请好友
  async apply(body, flag) {
    const { user, friend } = body;
    console.log(body);
    const [apply, count] = await this.applyRepository.findAndCount({
      where: {
        fromUser: user,
        toUser: friend,
      },
    });
    if (count === 0 && flag === 'apply') {
      const tempPush = await this.applyRepository.create({
        fromUser: user,
        toUser: friend,
      });
      this.applyRepository.save(tempPush);
    }
    return count;
  }

  setChat(payload) {
    return this.redisClient.set(payload.userId, payload.socketId);
  }
  getChat(userId) {
    return this.redisClient.get(userId);
  }
  async addMessage(payload) {
    const { message, toUser, fromUser, avatar } = payload;
    const tempMsg = await this.messageRepository.create({
      message,
      toUser,
      fromUser,
      avatar,
    });
    return this.messageRepository.save(tempMsg);
  }
  getMessage(payload) {
    const users = [payload.toUser, payload.fromUser];
    return this.messageRepository.find({
      where: { fromUser: In(users), toUser: In(users) },
      order: { addTime: 'ASC' },
    });
  }
  async findAll(query) {
    const { pageSize = 10, pageNum = 1, user } = query;
    const [rows, total] = await this.friendRepository
      .createQueryBuilder('friends')
      .where('friends.user = :user', { user })
      .leftJoinAndSelect('friends.friend', 'friend')
      .leftJoinAndSelect('friend.profile', 'profile')
      .skip((pageNum - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    return { rows, total };
  }

  findOne(user: string) {
    // return this.friendRepository
    //   .createQueryBuilder('friend')
    //   .where('friend.user = :user', { user })
    //   .leftJoinAndSelect('friend.friend', 'friends');
  }
  findUser(user: string) {
    return this.userService.findOne(+user);
  }

  update(id: number, updateFriendDto) {
    // return `This action updates a #${id} friend`;
  }

  remove(id: number) {
    // return `This action removes a #${id} friend`;
  }
}
